using System;
using Avalonia.Controls;
using IntegratedMeasuring.Pages;
using IntegratedMeasuring.Storage;
using IntegratedMeasuring.Utils;
using Avalonia.Interactivity;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Avalonia.Threading;

namespace IntegratedMeasuring;

public partial class MainWindow : Window
{
    // Windows API 函数声明
    [DllImport("user32.dll")]
    private static extern short GetAsyncKeyState(int vKey);
    
    // 加密狗配置
    private DongleHandler _dongleHandler;
    private System.Timers.Timer? _dongleCheckTimer;
    private bool _dongleRemovalDetected = false; // 添加标志位，避免重复弹窗
    
    // PLC通信配置
    private PLCCommunicationHelper? _plcHelper;
    
    // 虚拟键码
    private const int VK_CONTROL = 0x11;
    private const int VK_KEY_1 = 0x31;
    
    private MainPage? _mainPage;
    private bool _isHotKeyPressed = false;
    private System.Timers.Timer? _hotKeyTimer;

    public MainWindow()
    {
        InitializeComponent();
        
        // 初始化通知管理器
        NotificationHelper.Initialize(this);
        
        // 绑定页面事件
        LoginPage.LoginRequested += LoginPage_LoginRequested;
        MainPage.LogoutRequested += MainPage_LogoutRequested;
        
        //  初始化数据库
        BaseDataStorage.Instance.InitRuntimeTables();
        LogDataStorage.Instance.InitRuntimeTables();
        
        // 启动热键检测
        if (!ViewModels.Entity.GC.IsPLCMainControl) StartHotKeyDetection();
        
        Loaded += OnLoaded;
    }

    private async void OnLoaded(object? sender, RoutedEventArgs e)
    { 
        // 启动加密狗检测
        _dongleHandler = new DongleHandler(this);
        if (!await _dongleHandler.CheckDongleAsync(this))
        {
            Environment.Exit(0);
        }
        
       // 启动加密狗拔除检测
       StartDongleRemovalDetection();
        
        // 初始化PLC通信
        if (ViewModels.Entity.GC.IsPLCMainControl)
        {
            InitializePLCCommunication();
        }
    }
    
    /// <summary>
    /// 初始化PLC通信
    /// </summary>
    private void InitializePLCCommunication()
    {
        try
        {
            _plcHelper = new PLCCommunicationHelper();
            
            // 订阅PLC数据变化事件
            _plcHelper.DataChanged += OnPLCDataChanged;
            
            // 尝试连接PLC
            if (!_plcHelper.OpenConnection(out string? errorMsg))
            {
                NotificationHelper.ShowWarning("PLC连接失败", $"无法连接到PLC设备：{errorMsg}");
            }
            else
            {
                NotificationHelper.ShowSuccess("PLC连接成功", "PLC设备已连接并开始监控");
            }
        }
        catch (Exception ex)
        {
            NotificationHelper.ShowError("PLC初始化失败", ex.Message);
        }
    }
    
    /// <summary>
    /// PLC数据变化事件处理
    /// </summary>
    private void OnPLCDataChanged(object? sender, PLCDataChangedEventArgs e)
    {
        // 当PLC数据发生变化时，触发热键事件
        Dispatcher.UIThread.InvokeAsync(() =>
        {
            OnGlobalHotKeyPressed();
        });
    }
    
    /// <summary>
    /// 启动加密狗拔除检测
    /// </summary>
    private void StartDongleRemovalDetection()
    {
        _dongleCheckTimer = new System.Timers.Timer(1000); // 每秒检查一次
        _dongleCheckTimer.Elapsed += async (sender, e) =>
        {
            await Dispatcher.UIThread.InvokeAsync(async () =>
            {
                await CheckDongleRemoval();
            });
        };
        _dongleCheckTimer.Start();
    }
    
    /// <summary>
    /// 检查加密狗是否被拔除
    /// </summary>
    private async Task CheckDongleRemoval()
    {
        try
        {
            // 如果已经检测到拔除，直接返回
            if (_dongleRemovalDetected)
            {
                return;
            }
            
            // 使用静默检测方法，不显示弹窗
            if (!_dongleHandler.CheckDongle())
            {
                // 设置标志位，避免重复弹窗
                _dongleRemovalDetected = true;
                
                // 加密狗无效或被拔除，显示提示并关闭软件
                var confirmDialog = new ConfirmDialog("加密狗已拔出或无效，软件即将关闭！");
                await confirmDialog.ShowDialog<bool?>(this);
                Environment.Exit(0);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"检查加密狗状态时出错: {ex.Message}");
        }
    }
    
    private void LoginPage_LoginRequested(object? sender, LoginEventArgs e)
    {
        // 切换到主功能页面
        LoginPage.IsVisible = false;
        MainPage.IsVisible = true;
        
        // 保存MainPage引用
        _mainPage = MainPage;
        
        // 更新窗口标题
        this.Title = $"扶光科技综测数据采集系统 - {e.Instrument}";
    }

    private void MainPage_LogoutRequested(object? sender, EventArgs e)
    {
        // 返回登录页面
        LoginPage.IsVisible = true;
        MainPage.IsVisible = false;
        
        // 清除MainPage引用
        _mainPage = null;
        
        // 恢复窗口标题
        Title = "扶光科技综测数据采集系统";
    }
    
    /// <summary>
    /// 启动热键检测
    /// </summary>
    private void StartHotKeyDetection()
    {
        // 使用定时器检测热键
        _hotKeyTimer = new System.Timers.Timer(50); // 50ms检查一次
        _hotKeyTimer.Elapsed += async (sender, e) =>
        {
            try
            {
                await Dispatcher.UIThread.InvokeAsync(() =>
                {
                    CheckHotKey();
                });
            } catch (Exception ex)
            {
                // Console.WriteLine($"检查热键时出错: {ex.Message}");
            }

        };
        _hotKeyTimer.Start();
    }
    
    /// <summary>
    /// 检查热键状态
    /// </summary>
    private void CheckHotKey()
    {
        try
        {
            // 检查Ctrl+1是否被按下
            bool ctrlPressed = (GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0;
            bool key1Pressed = (GetAsyncKeyState(VK_KEY_1) & 0x8000) != 0;
            
            if (ctrlPressed && key1Pressed && !_isHotKeyPressed)
            {
                _isHotKeyPressed = true;
                OnGlobalHotKeyPressed();
            }
            else if (!ctrlPressed || !key1Pressed)
            {
                _isHotKeyPressed = false;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"检查热键时出错: {ex.Message}");
        }
    }
    
    /// <summary>
    /// 处理热键事件
    /// </summary>
    private void OnGlobalHotKeyPressed()
    {
        // 检查当前是否在工作台页面
        if (_mainPage != null && MainPage.IsVisible)
        {
            // 转发给MainPage处理
            _mainPage.OnHotKeyPressed(this, EventArgs.Empty);
        }
    }
    
    /// <summary>
    /// 显示全局加载动画
    /// </summary>
    /// <param name="loadingText">加载提示文字</param>
    public void ShowGlobalLoading(string loadingText = "正在处理中，请稍后...")
    {
        if (GlobalLoadingText != null)
        {
            GlobalLoadingText.Text = loadingText;
        }
        if (GlobalLoadingOverlay != null)
        {
            GlobalLoadingOverlay.IsVisible = true;
        }
    }
    
    /// <summary>
    /// 隐藏全局加载动画
    /// </summary>
    public void HideGlobalLoading()
    {
        if (GlobalLoadingOverlay != null)
        {
            GlobalLoadingOverlay.IsVisible = false;
        }
    }
    
    /// <summary>
    /// 窗口关闭时清理资源
    /// </summary>
    protected override void OnClosed(EventArgs e)
    {
        // 停止热键检测定时器
        _hotKeyTimer?.Stop();
        _hotKeyTimer?.Dispose();
        
        // 停止加密狗检测定时器
        _dongleCheckTimer?.Stop();
        _dongleCheckTimer?.Dispose();
        
        // 释放PLC通信资源
        _plcHelper?.Dispose();
        
        _dongleHandler?.Dispose();
        
        base.OnClosed(e);
    }
}